<template>
  <div>
    <el-empty v-if="dayItems.length == 0" description="无数据" />
    <el-timeline v-else>
      <el-timeline-item
        v-for="dayItem in dayItems"
        :timestamp="`${dayItem.date} 总扇区时长: ${(
          dayItem.accumulation / 60
        ).toFixed(1)} 小时`"
        placement="top"
        size="large"
        icon="Calendar"
      >
        <div class="card-slim timeline-item">
          <DayChart
            :cellItems="dayItem.cellItems"
            :maxValue="maxValue"
            :chartWidth="chartWidth"
            :chartHeight="chartHeight"
          />
        </div>
      </el-timeline-item>
    </el-timeline>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from "vue";

import useSeatStore from "@/store/seat.js";
const seatStore = useSeatStore();

import useCommonStore from "@/store/common.js";
const commonStore = useCommonStore();

import DayChart from "./DayChart.vue";
import generateDayItems from "./generateDayItems.js";

const dayItems = ref([]);
const dayCount = ref(0);

const maxValue = computed(() => {
  let max = 0;
  dayItems.value.forEach((dayItem) => {
    max = Math.max(max, dayItem.maxValue);
  });
  return max;
});

const chartWidth = computed(
  () =>
    (
      commonStore.clientWidth -
      (commonStore.showSidebar ? 200 : 0) -
      96
    ).toFixed() + "px"
);

const chartHeight = computed(
  () =>
    (dayCount.value > 0
      ? Math.max(
          Math.floor(
            (commonStore.clientHeight - 296) / dayCount.value -
              dayCount.value * 16
          ),
          200
        )
      : 0) + "px"
);

const generateData = () => {
  dayItems.value = [];
  const rawData = seatStore.historyView.queryResult;
  const stepMinutes = seatStore.historyView.summaryConfig.stepMinutes;
  const startDate = seatStore.historyView.queryConfig.dateRange[0];
  const endDate = seatStore.historyView.queryConfig.dateRange[1];
  const valueType = seatStore.historyView.summaryConfig.valueType;
  const list = generateDayItems(
    rawData,
    stepMinutes,
    startDate,
    endDate,
    valueType
  ).filter((item) => item.accumulation > 0);
  dayCount.value = list.length;

  let timer = setInterval(() => {
    if (dayItems.value.length < list.length) {
      dayItems.value.push(list[dayItems.value.length]);
    } else {
      clearInterval(timer);
    }
  }, 500);
};

// 监听数据变化，更新图表
watch(
  () => [
    seatStore.historyView.queryResult,
    seatStore.historyView.summaryConfig,
    chartWidth,
  ],
  () => generateData(),
  { deep: true }
);
</script>

<style scoped>
@import "../card.css";

.timeline-item {
  padding: 4px 0 0 8px;
}
</style>
